//#define _CRTDBG_MAP_ALLOC
#include "StdAfx.h"
#include "HoughTransform.h"


HoughTransform::HoughTransform(void)
{

}

IplImage* HoughTransform::applyHoughTransform(IplImage* frameImage)
{
	IplImage* src=cvCreateImage( cvGetSize(frameImage), 8, 1 );;
	IplImage* dst;
    IplImage* color_dst;
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* lines = 0;

	cvCvtColor( frameImage, src, CV_RGB2GRAY );

	dst = cvCreateImage( cvGetSize(src), 8, 1 );
    color_dst = cvCreateImage( cvGetSize(src), 8, 3 );

    cvCanny( src, dst, 50, 200, 3 );
    cvCvtColor( dst, color_dst, CV_GRAY2BGR );

	lines = cvHoughLines2( dst, storage, CV_HOUGH_STANDARD, 1, CV_PI/180, 100, 0, 0 );

    for(int i = 0; i < MIN(lines->total,100); i++ )
    {
        float* line = (float*)cvGetSeqElem(lines,i);
        float rho = line[0];
        float theta = line[1];
        CvPoint pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 3, CV_AA, 0 );
    }

	cvShowImage( "Hough", color_dst );

	cvReleaseImage(&src);
	cvReleaseImage(&dst);
	//cvReleaseImage(&color_dst);
	cvReleaseMemStorage(&storage);
return color_dst;

}
